﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using FineUI;
using SysManage.BLL;
using ZHDJ.Core.Caching;
using ZHDJ.Data.Models.Box;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;

namespace SysManage.Module.Org
{
    public partial class PartyOrgMemberList : BLL.PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyOrgMemberView";
            }
        }

        /// <summary>
        /// 用户类型 1、困难党员 2、党代表 3、志愿者、4、在职党员
        /// </summary>
        public string MemberType
        {
            get
            {
                return Request.QueryString["MemberType"] ?? "0";

            }
        }

        public bool? isHardParty { get; set; }

        public bool? isPartyDeputy { get; set; }

        public bool? isVolunteer { get; set; }

        public bool? isIncumbency { get; set; }
        public bool? isPartyWorker { get; set; }

        /// <summary>
        /// 村代表
        /// </summary>
        public bool? IsFaipule { get; set; }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdParentBranchID.Text = this.BranchID;
                BindData();
                LoadData();
            }
        }

        private void BindData()
        {
            // 权限检查
            CheckPowerWithButton("PartyOrgMemberDelete", btnDeleteSelected);
            CheckPowerWithButton("PartyOrgMemberAdd", btnNew);
            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid1);
            btnNew.OnClientClick = Window1.GetShowReference("PartyOrgMemberEdit.aspx?BranchID=" + BranchID + "&MemberType=" + MemberType, "新增用户");
            btnImport.OnClientClick = wImport.GetShowReference("PartyOrgMemberImport.aspx", "导入党员信息");

            // 每页记录数
            Grid1.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();
            BindTree();

        }

        private void LoadData()
        {
            InitPara();

            var ds = PartyOrgMember.GetMemberByBranchId(hdParentBranchID.Text,
                txtTitle.Text, Grid1.PageIndex, Grid1.PageSize, 0, isPartyWorker, "", isHardParty, isPartyDeputy, isVolunteer, isIncumbency,IsFaipule);
            Grid1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            Grid1.DataSource = ds.Tables[0];
            Grid1.DataBind();

        }

        public void InitPara()
        {
            isPartyWorker = isHardParty = isPartyDeputy = isVolunteer = isIncumbency = null;
            switch (MemberType)
            {
                case "1": isHardParty = true; break;
                case "2": isPartyDeputy = true; break;
                case "3": isVolunteer = true; break;
                case "4": isIncumbency = true; break;
                case "5": IsFaipule = true; break;
            }
            if (MemberType != "0")
            {
                Grid1.Columns[6].Hidden = true;
                Grid1.Columns[8].Hidden = true;
                btnDeleteSelected.Hidden = true;
                btnNew.Hidden = true;
                this.btnDownTmeplate.Hidden = true;
                this.btnImport.Hidden = true;
                //Grid1.Columns[7].HeaderText = "查看";
            }
            if (!string.IsNullOrEmpty(ddlIsPartyWorker.SelectedValue))
            {
                isPartyWorker = ddlIsPartyWorker.SelectedValue == "1";
            }
        }

        private void BindTree()
        {
            TreeControlBusiness tree = new TreeControlBusiness("BranchID", "ParentBranchID", "BranchName", true, CacheKeys.Cache_Branch_Tree);
            tree.EnableClickEvent = true;
            tree.BindTreeBranch(TreeBranch);
            if (!string.IsNullOrEmpty(BranchID))
            {
                var n = TreeBranch.FindNode(BranchID);

                TreeBranch.Nodes.Clear();
                if (n != null)
                    TreeBranch.Nodes.Add(n);
            }
            if (TreeBranch.Nodes.Count > 0)
            {
                //展开第一层
                TreeBranch.Nodes[0].Expanded = true;
            }
        }



        #endregion

        #region Events
        protected void TreeBranch_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            hdParentBranchID.Text = e.Node.NodeID;
            btnNew.OnClientClick = Window1.GetShowReference("PartyOrgMemberEdit.aspx?BranchID=" + hdParentBranchID.Text + "&MemberType=" + MemberType, "新增用户");

            LoadData();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithWindowField("PartyOrgMemberEdit", Grid1, "editField");
            CheckPowerWithLinkButtonField("PartyOrgMemberDelete", Grid1, "deleteField");
            CheckPowerWithWindowField("PartyOrgMemberChangePassword", Grid1, "changePasswordField");

        }

        protected void Grid1_PreRowDataBound(object sender, FineUI.GridPreRowEventArgs e)
        {
            var member = e.DataItem as DataRowView;

            // 不能删除超级管理员
            if (Convert.ToString(member["UserName"]).Trim() == "admin")
            {
                FineUI.LinkButtonField deleteField = Grid1.FindColumn("deleteField") as FineUI.LinkButtonField;
                deleteField.Enabled = false;
                deleteField.ToolTip = "不能删除超级管理员！";
            }

            var field = Grid1.FindColumn("editField") as WindowField;
            if (field != null)
            {
                field.DataIFrameUrlFormatString = "PartyOrgMemberEdit.aspx?id={0}&MemberType=" + MemberType +
                                                  "&BranchID=" + BranchID;
            }

        }

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            LoadData();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyOrgMemberDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            DB.PartyOrgMembers.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyOrgMembers.Remove(u));
            DB.SaveChanges();
            //DB.Users.Delete(u => ids.Contains(u.ID));


            // 重新绑定表格
            LoadData();
        }

        protected void btnEnableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(true);
        }

        protected void btnDisableUsers_Click(object sender, EventArgs e)
        {
            SetSelectedUsersEnableStatus(false);
        }


        private void SetSelectedUsersEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyOrgMemberEdit"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            DB.Users.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => u.Enabled = enabled);
            DB.SaveChanges();
            //DB.Users.Update(u => ids.Contains(u.ID), u => new User { Enabled = enabled });

            // 重新绑定表格
            LoadData();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string userID = GetSelectedDataKeyID(Grid1);
            string userName = GetSelectedDataKey(Grid1, 1);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPower("PartyOrgMemberDelete"))
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                if (userName == "admin")
                {
                    Alert.ShowInTop("不能删除默认的系统管理员（admin）！");
                }
                else
                {
                    var T = DB.PartyOrgMembers.FirstOrDefault(a => a.ID == userID);
                    DB.PartyOrgMembers.Remove(T);
                    DB.SaveChanges();
                    LoadData();
                }
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            hdParentBranchID.Text = "";
            LoadData();
        }
        protected void Window1_Close(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void rblEnableStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }


        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);

            LoadData();
        }

        #endregion

        protected string GetGender(object Gender)
        {
            var d = Convert.ToString(Gender);
            if (d == "1")
            {
                return "女";
            }
            else if (d == "0")
            {
                return "男";
            }
            return "未知";
        }


    }
}